/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import 'dart:async';

import 'package:flutter/material.dart';
import 'folder_options.dart';
import 'folder_plugin.dart';

///FoldSplitContainer分栏布局，实现折叠屏二分栏、三分栏在展开态、悬停态以及折叠态的区域控制。
class FoldSplitContainer extends StatefulWidget {
  ///主要区域
  final Widget primary;

  ///次要区域
  final Widget secondary;

  ///扩展区域回调函数，不传入的情况，没有对应区域
  final Widget? extra;

  ///折叠态布局信息
  final FoldedRegionLayoutOptions foldedLayoutOptions;

  ///展开态布局信息
  final ExpandedRegionLayoutOptions expandedLayoutOptions;

  ///悬停态布局信息
  final HoverModeRegionLayoutOptions hoverModeLayoutOptions;

  ///折叠屏进入或退出悬停模式时触发的回调函数
  final ValueChanged<FoldStatus>? onHoverStatusChange;

  const FoldSplitContainer({
    Key? key,
    required this.primary,
    required this.secondary,
    this.extra,
    required this.foldedLayoutOptions,
    required this.expandedLayoutOptions,
    required this.hoverModeLayoutOptions,
    this.onHoverStatusChange,
  }) : super(key: key);

  @override
  State<StatefulWidget> createState() => _FoldSplitContainerState();
}

class _FoldSplitContainerState extends State<FoldSplitContainer> {
  late StreamSubscription<FoldingFeature> _subscription;
  var foldingFeature = FoldingFeature();

  @override
  void initState() {
    super.initState();
    _subscription =
        FolderStackPlugin.folderStateEvents.listen((FoldingFeature status) {
      if (status.state != foldingFeature.state ||
          status.orientation != foldingFeature.orientation) {
        setState(() {
          foldingFeature = status;
        });
        widget.onHoverStatusChange?.call(foldingFeature.state);
      }
    });
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    switch (foldingFeature.state) {
      case FoldStatus.expanded:
        return _buildExpandedLayout();
      case FoldStatus.halfFolded:
        return _buildHoverModeLayout();
      default:
        return _buildFoldedRegionLayout();
    }
  }

  // Helper to convert ratio to integer flex factor
  int _ratioToFlex(double ratio) {
    // Clamp ratio, convert to percentage, ensure minimum flex of 1
    final flex = (ratio * 10).round();
    return flex > 0 ? flex : 1;
  }

  /// 悬停态布局信息
  Widget _buildHoverModeLayout() {
    var topWidget = _buildTopWidget();
    var bottomWidget = _buildBottomWidget();
    var mediaQuery = MediaQuery.of(context);
    var foldBounds = Rect.zero;
    var startPaneFlex = 1;
    var endPaneFlex = 1;
    if (foldingFeature.orientation == Axis.horizontal) {
      foldBounds = _calculateFoldBounds(mediaQuery);
      startPaneFlex = (foldBounds.top / mediaQuery.size.height * 100).round();
      endPaneFlex = ((mediaQuery.size.height - foldBounds.bottom) /
              mediaQuery.size.height *
              100)
          .round();
      startPaneFlex = startPaneFlex > 0 ? startPaneFlex : 1;
      endPaneFlex = endPaneFlex > 0 ? endPaneFlex : 1;
    }
    return Flex(
      direction: Axis.vertical,
      children: <Widget>[
        Expanded(
          flex: startPaneFlex,
          child: topWidget,
        ),
        SizedBox(height: foldBounds.height, width: foldBounds.width),
        Expanded(
          flex: endPaneFlex,
          child: bottomWidget,
        ),
      ],
    );
  }

  /// 构建顶部区域
  Widget _buildTopWidget() {
    var topWidget = widget.primary;
    if (widget.extra != null && widget.hoverModeLayoutOptions.showExtraRegion) {
      if (widget.hoverModeLayoutOptions.extraRegionPosition ==
          ExtraRegionPosition.top) {
        topWidget = Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Expanded(
              flex: _ratioToFlex(
                  widget.hoverModeLayoutOptions.horizontalSplitRatio),
              child: widget.primary,
            ),
            Expanded(
              flex: _ratioToFlex(
                  1.0 - widget.hoverModeLayoutOptions.horizontalSplitRatio),
              child: widget.extra!,
            ),
          ],
        );
      }
    }
    return topWidget;
  }

  /// 构建底部区域
  Widget _buildBottomWidget() {
    var bottomWidget = widget.secondary;
    if (widget.extra != null && widget.hoverModeLayoutOptions.showExtraRegion) {
      if (widget.hoverModeLayoutOptions.extraRegionPosition !=
          ExtraRegionPosition.top) {
        bottomWidget = Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Expanded(
              flex: _ratioToFlex(
                  widget.hoverModeLayoutOptions.horizontalSplitRatio),
              child: widget.secondary,
            ),
            Expanded(
              flex: _ratioToFlex(
                  1.0 - widget.hoverModeLayoutOptions.horizontalSplitRatio),
              child: widget.extra!,
            ),
          ],
        );
      }
    }
    return bottomWidget;
  }

  /// 计算折叠屏痕迹
  Rect _calculateFoldBounds(MediaQueryData mediaQuery) {
    var foldBounds = Rect.fromLTRB(
      foldingFeature.bounds.left / mediaQuery.devicePixelRatio,
      foldingFeature.bounds.top / mediaQuery.devicePixelRatio,
      foldingFeature.bounds.right / mediaQuery.devicePixelRatio,
      foldingFeature.bounds.bottom / mediaQuery.devicePixelRatio,
    );
    if (foldBounds.top > mediaQuery.size.height) {
      foldBounds = Rect.fromLTWH(
          0, mediaQuery.size.height / 2, mediaQuery.size.width, 1);
    }
    return foldBounds;
  }

  /// 展开态布局信息
  Widget _buildExpandedLayout() {
    if (widget.expandedLayoutOptions.isExtraRegionPerpendicular &&
        widget.extra != null) {
      return _buildMainAreaWithExtraPerpendicular();
    } else {
      return _buildMainAreaWithExtraHorizontal();
    }
  }

  /// 构建主区域和扩展区域（垂直布局）
  Widget _buildMainAreaWithExtraPerpendicular() {
    return Flex(
      direction: Axis.horizontal,
      children: <Widget>[
        Expanded(
          flex: _ratioToFlex(widget.expandedLayoutOptions.horizontalSplitRatio),
          child: _buildMainArea(),
        ),
        Expanded(
          flex: _ratioToFlex(
              1.0 - widget.expandedLayoutOptions.horizontalSplitRatio),
          child: widget.extra!,
        ),
      ],
    );
  }

  /// 构建主区域和扩展区域（水平布局）
  Widget _buildMainAreaWithExtraHorizontal() {
    var topWidget = widget.primary;
    var bottomWidget = widget.secondary;
    if (widget.extra != null) {
      if (widget.expandedLayoutOptions.extraRegionPosition ==
          ExtraRegionPosition.top) {
        topWidget = _buildExtraArea(widget.primary);
      } else {
        bottomWidget = _buildExtraArea(widget.secondary);
      }
    }
    return Flex(
      direction: Axis.vertical,
      children: <Widget>[
        Expanded(
          flex: _ratioToFlex(widget.expandedLayoutOptions.verticalSplitRatio),
          child: topWidget,
        ),
        Expanded(
          flex: _ratioToFlex(
              1.0 - widget.expandedLayoutOptions.verticalSplitRatio),
          child: bottomWidget,
        ),
      ],
    );
  }

  /// 构建主区域
  Widget _buildMainArea() {
    return Flex(
      direction: Axis.vertical,
      children: <Widget>[
        Expanded(
          flex: _ratioToFlex(widget.expandedLayoutOptions.verticalSplitRatio),
          child: widget.primary,
        ),
        Expanded(
          flex: _ratioToFlex(
              1.0 - widget.expandedLayoutOptions.verticalSplitRatio),
          child: widget.secondary,
        ),
      ],
    );
  }

  /// 构建扩展区域
  Widget _buildExtraArea(Widget mainWidget) {
    return Flex(
      direction: Axis.horizontal,
      children: <Widget>[
        Expanded(
          flex: _ratioToFlex(widget.expandedLayoutOptions.horizontalSplitRatio),
          child: mainWidget,
        ),
        Expanded(
          flex: _ratioToFlex(
              1.0 - widget.expandedLayoutOptions.horizontalSplitRatio),
          child: widget.extra!,
        ),
      ],
    );
  }

  ///折叠态布局信息
  Widget _buildFoldedRegionLayout() {
    double activePerpendicularRatio =
        widget.foldedLayoutOptions.verticalSplitRatio;
    return Flex(
      direction: Axis.vertical,
      children: <Widget>[
        Expanded(
          flex: _ratioToFlex(activePerpendicularRatio),
          child: widget.primary,
        ),
        Expanded(
          // Ensure flex > 0
          flex: _ratioToFlex(1.0 - activePerpendicularRatio),
          child: widget.secondary,
        ),
      ],
    );
  }
}
